from random import randint

import pygame
from pygame import Surface

from game_objects.alien import Alien
from game_objects.bullet import Bullet


def config_screen(settings: object) -> Surface:
    """配置游戏屏幕，返回一个屏幕对象是 SurfaceType 类型"""
    pygame.init()
    pygame.display.set_caption(settings.title['title'])  # 设置游戏窗体标题
    screen = pygame.display.set_mode((settings.sizes['screen_width'],
                                      settings.sizes['screen_height']))  # 设置游戏窗体大小

    return screen


def update_screen(settings: object,
                  screen: object,
                  ship: object,
                  bullets: object,
                  aliens: object) -> None:
    """
    更新屏幕上的图像，并切换到新屏幕
    :param settings: 游戏设置对象
    :param screen: 屏幕对象
    :param ship: 飞船对象
    :param bullets: 子弹对象组（Group）
    :param aliens: 外星人敌人对象组（Group）
    """
    bg_image = pygame.image.load(settings.image_paths['bg_image']).convert_alpha()
    screen.blit(bg_image, (0, 0))  # 设置背景图片
    ship.draw()  # 绘制飞船
    bullet_draw(bullets)  # 绘制子弹编组
    aliens.draw(screen)  # 绘制外星人编组
    pygame.display.flip()  # 更新屏幕


def bullet_draw(bullets: object) -> None:
    """
    绘制子弹
    :param bullets: 子弹编组
    """
    for bullet in bullets.sprites():  # 绘制子弹
        bullet.draw()


def bullet_fire(bullets: object, screen: object, settings: object, ship: object) -> None:
    """
    发射子弹，创建新子弹对象，添加到编组 bullets 中
    :param bullets: 子弹编组
    :param screen: 屏幕对象
    :param settings: 游戏设置对象
    :param ship: 飞船对象
    """
    new_bullet = Bullet(screen, settings, ship)
    bullets.add(new_bullet)


def create_fleet(screen: object, settings: object, aliens: object) -> None:
    """创建外星人飞船舰队"""
    alien = Alien(screen, settings)
    current_x = alien.rect.x
    current_y = alien.rect.y

    interval_width = randint(50, 120)

    while current_x < (settings.sizes['screen_width'] - interval_width):  # 防止外星人飞船超出屏幕
        interval_width = randint(50, 120)
        interval_height = randint(-10, 10)  # 外星飞船与屏幕上边缘的距离

        new_alien = Alien(screen, settings)
        new_alien.rect.x = current_x
        new_alien.rect.y = current_y
        aliens.add(new_alien)

        current_x += alien.rect.width + interval_width
        new_current_y = current_y + interval_height
        if new_current_y > new_alien.rect.height / 4:
            current_y = new_current_y


def show_start_screen(start_screen: object) -> None:
    """显示开始屏幕"""
    start_screen.draw()
    pygame.display.flip()
